package com.cloudservice.ccs.biz.impl;

import com.cloudservice.ccs.biz.ICustomerServiceDesignationBiz;
import com.cloudservice.ccs.biz.ISessionBiz;
import com.cloudservice.ccs.biz.IVisitorInfoBiz;
import com.cloudservice.ccs.entity.Session;
import com.cloudservice.ccs.entity.VisitorInfo;
import com.cloudservice.ccs.exception.CustomerServiceException;
import com.cloudservice.ccs.exception.VisitorInfoException;
import com.cloudservice.ccs.mapper.VisitorInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class VisitorInfoImpl implements IVisitorInfoBiz {
	@Autowired
	VisitorInfoMapper visitorInfoMapper;

	@Autowired
	ISessionBiz sessionBiz;

	@Autowired
	ICustomerServiceDesignationBiz customerServiceDesignationBiz;

	@Override
	public Integer save(VisitorInfo visitorInfo) {
		boolean originallyExisting = true;
		VisitorInfo foundVisitorInfo = visitorInfoMapper.getOne(visitorInfo.getIp());
		if (foundVisitorInfo == null) {
			int result = visitorInfoMapper.save(visitorInfo);
			if (result == 0) {
				throw new VisitorInfoException("创建访客信息失败");
			}
			originallyExisting = false;
			foundVisitorInfo = visitorInfoMapper.getOne(visitorInfo.getIp());
		}
		try {
			Integer sessionId = customerServiceDesignationBiz.createSession(foundVisitorInfo);
			visitorInfoMapper.update(foundVisitorInfo.getIp(), foundVisitorInfo);
			return sessionId;
		} catch (Exception e) {
			if (!originallyExisting) {
				visitorInfoMapper.delete(visitorInfo.getIp());
			}
			throw e;
		}
	}

	@Override
	public void update(String ip, VisitorInfo visitorInfo) {
		int result = visitorInfoMapper.update(ip,visitorInfo);
		if (result == 0) {
			throw new VisitorInfoException("Update VisitorInfo entity error");
		}
	}

	@Override
	public void delete(String ip) {
		int result = visitorInfoMapper.delete(ip);
		if (result == 0) {
			throw new VisitorInfoException("Delete VisitorInfo entity error");
		}
	}

	@Override
	public void partialUpdate(String ip, Map<String, Object> fields) {

		int result = visitorInfoMapper.partialUpdate(ip, fields);
		if (result == 0) {
			throw new CustomerServiceException("访客信息失败");
		}
	}

	@Override
	public VisitorInfo getOne(String ip) {
		VisitorInfo visitorInfo = visitorInfoMapper.getOne(ip);
		if (visitorInfo == null) {
			throw new VisitorInfoException("Get VisitorInfo entity error: no such entity");
		}
		return visitorInfo;
	}

	@Override
	public List<VisitorInfo> getAll() {
		return visitorInfoMapper.getAll();
	}

	@Override
	public List<VisitorInfo> conditionQuery(Map<String,Object> fields){
		List<VisitorInfo> result = visitorInfoMapper.conditionQuery(fields);
		if (result==null) {
			throw new VisitorInfoException("访客条件查询发生错误");
		}
		return result;
	}
}
